//
//  RYCUncaughtExceptionHandler.m
//  TestAppIDP
//
//  Created by hemingway payegis on 13-4-19.
//  Copyright (c) 2013年 payegis. All rights reserved.
//

#import "RYCUncaughtExceptionHandler.h"

static NSString *applicationDocumentsDirectory();
static void UncaughtExceptionHandler(NSException *exception);

@interface RYCUncaughtExceptionHandler ()
+ (NSUncaughtExceptionHandler*)getHandler;
+ (void)writeToFile:(NSString*)content;
+ (void)removeFile;
@end


@implementation RYCUncaughtExceptionHandler

+ (void)setDefaultHandler
{
    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
}

+ (NSUncaughtExceptionHandler*)getHandler
{
    return NSGetUncaughtExceptionHandler();
}

+ (NSString*)lastExceptionDescrption
{
    NSString *path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"exception.txt"];
    if (NO == [[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        return nil;
    }
    
    NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    return content;
}

+ (void)lastExceptionDidHandled
{
    [RYCUncaughtExceptionHandler removeFile];
}

+ (void)writeToFile:(NSString*)content
{
    NSString *path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"exception.txt"];
    NSError* error = nil;
    [content writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error)
    {
        NSLog(@"%@",error);
    }
}

+ (void)removeFile
{
    NSString *path = [applicationDocumentsDirectory() stringByAppendingPathComponent:@"exception.txt"];
    NSError* error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    if (error)
    {
        NSLog(@"%@",error);
    }
}
@end

NSString *applicationDocumentsDirectory() {
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

void UncaughtExceptionHandler(NSException *exception) {
    NSArray *arr = [exception callStackSymbols];
    NSString *reason = [exception reason];
    NSString *name = [exception name];
    
    NSString* appId = [[NSBundle mainBundle] bundleIdentifier];
    NSString *content = [NSString stringWithFormat:@"appIdentifier:%@\nname:\n%@\nreason:\n%@\ncallStackSymbols:\n%@",
                         appId,name,reason,[arr componentsJoinedByString:@"\n"]];
    
    //除了可以选择写到应用下的某个文件，通过后续处理将信息发送到服务器等
    //还可以选择调用发送邮件的的程序，发送信息到指定的邮件地址
    //或者调用某个处理程序来处理这个信息
    [RYCUncaughtExceptionHandler writeToFile:content];
}

